# -*- coding: utf-8 -*-
# @Time    : 2020/5/25 下午5:36
# @Author  : Kevin Liu
# @Email   : liuwenlongfox@163.com
import datetime
import json,threading
import os
import time
from utils import Curl
from prometheus_client import start_http_server,Summary,Gauge
REQUEST_TIME = Summary('request_process_sencods','Time spent processing request')
def send_request(curl,case,token,gauge,duration):
    for case_name, case_config in case.items():
        # print(case_name, case_config)
        result = curl.send_requests(case_config,token)
        print(result.text)
        if result:
            status_code = result.status_code

            # g.labels(api=case_name)
            if status_code == 200:
                gauge.labels(apiModule=case_name).set(1)
                duration.labels(apiModule=case_name).set(result.elapsed.seconds)
            else:
                gauge.labels(apiModule=case_name).set(0)
                duration.labels(apiModule=case_name).set(result.elapsed.seconds)
        else:
            gauge.labels(apiModule=case_name).set(0)
            duration.labels(apiModule=case_name).set(result.elapsed.seconds)
@REQUEST_TIME.time()
def check_cmdb_api_status(curl,gauge,duration):
    token = curl.get_token()
    config = curl.parse_config()
    for case in config.get('cases'):
        # send_request(curl,case,token,gauge,duration)
        thread = threading.Thread(target=send_request,args=(curl,case,token,gauge,duration))
        thread.start()
def perform_check(curl,gauge,duration):
    print("start at",datetime.datetime.now(),threading.currentThread().name)
    config = curl.parse_config()
    print(config)
    scrape_interval = config.get('config').get('scrape_interval')
    check_cmdb_api_status(curl, gauge, duration)
    time.sleep(scrape_interval)
if __name__ == '__main__':
    start_http_server(80)
    gauge = Gauge('API', 'API Status', ['apiModule'])
    duration = Gauge('API_ResponseTime','API Response Time',['apiModule'])
    config_base_dir = os.path.join(os.path.abspath('.'),'config_dir')
    while True:
        threads_set = []
        curls = []
        i = 0
        for file in os.listdir(config_base_dir):
            curl = Curl(os.path.join(config_base_dir, file))
            thread = threading.Thread(target=perform_check,args=(curl,gauge,duration,))
            threads_set.append(thread)
        for t in threads_set:
            t.start()
        t.join()




